<?php
namespace app\common\model;
use app\common\cache\CacheData;

class LevelCoinConfig extends Base
{

	public function cacheData(){
        $data = $this -> select();
        if($data){
            foreach($data as &$value):
                $value = $value->toArray();
            endforeach;
        }
        return $data;
    }

    public static function typeData($type='register',$id=null){
        $CACHE = CacheData::getInstance('LevelCoinConfig');
        $CACHE -> updateCache();
        $cacheData = $CACHE -> readCache();
        $data = [];
        foreach($cacheData as $value):
            if($value['type']!=$type)
                continue;
            $value['coin_name'] = Coin::coinData($value['coin_id'])['coin_name'];
            $value['level_name'] = Level::levelData($value['level_id'])['level_name'];
            $data[$value['id']] = $value;
        endforeach;
        if(is_null($id)){
            return $data;
        }else{
            return $data[$id];
        }
        
    }

    /**
     * 基于等级的货币配置缓存 by type
     * @param  [type] $type [description]
     * @return [type]     [description]
     */
    public static function levelCoinConfigByType($type='register'){
        $CACHE = CacheData::getInstance('LevelCoinConfig');
        $cacheData = $CACHE -> readCache();
        $configData = [];
        foreach($cacheData as $cache):
            $configData[$cache['type']][] = $cache;
        endforeach;

        if(isset($configData[$type]))
            return $configData[$type];
        else
            return false;
    }

    /**
     * 按类型查询配置 按等级分组
     * @return [type] [description]
     */
    public static function levelCoinConfigByTypeWithLevel($type='register'){
    
        $levelsData = Level::levelData();
        $coinConfig = self::levelCoinConfigByType($type);
        $result = [];
        foreach($levelsData as $level):
            $configs = [];
            foreach($coinConfig as $config):
                if($config['level_id']==$level['id']){
                    $coinData = Coin::coinData($config['coin_id']);
                    $config['coin_name'] = $coinData['coin_name'];
                    $configs[] = $config;
                }
            endforeach;
            $level['config'][$type] = $configs;
            $result[$level['id']] = $level;
        endforeach;
        return $result;
    }

    /**
     * 按等级与类型查询
     * @param  [type] $level_id [description]
     * @param  [type] $type     [description]
     * @return [type]           [description]
     */
    public static function configByLevelType($level_id,$type){
        $typeConfig = self::levelCoinConfigByTypeWithLevel($type);
        if(isset($typeConfig[$level_id]))
            return $typeConfig[$level_id];
        return $typeConfig;
    }

}
